package com.zaofan.controller;

import com.zaofan.bean.Admin;
import com.zaofan.bean.OpenBuilder;
import com.zaofan.service.OpenBuilderService;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;

import org.apache.commons.dbutils.QueryRunner;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zaofan.utils.C3p0DataSourceUtils.getDataSource;

@WebServlet("/builder")
public class OpenBuilderController extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private OpenBuilderService openBuilderService = new OpenBuilderService();

	protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			List<OpenBuilder> builders = openBuilderService.findAll(params);
			
			Collections.sort(builders, new Comparator<OpenBuilder> () {

				@Override
				public int compare(OpenBuilder o1, OpenBuilder o2) {
					return Integer.valueOf(o1.getSort()).compareTo(Integer.valueOf(o2.getSort()));
				}
				
			});
			Long count = openBuilderService.count(params);
			JsonUtils.writeSuccessPageJson("查询成功", builders, count, response);

		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

	protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			OpenBuilder builder = WebUtils.write2bean(request, OpenBuilder.class);
			openBuilderService.add(builder);
			JsonUtils.writeSuccessJson("添加成功", "", response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("添加失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("添加失败!!", response);
	}

	protected void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			OpenBuilder builder = WebUtils.write2bean(request, OpenBuilder.class);
			openBuilderService.update(builder);
			JsonUtils.writeSuccessJson("修改成功", "", response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("修改失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("修改失败!!", response);
	}

	protected void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String id_s = request.getParameter("id");
			Integer id = Integer.valueOf(id_s);
			OpenBuilder builder = openBuilderService.findById(id);
			JsonUtils.writeSuccessJson("查询成功", builder, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询成功!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("查询成功!!", response);
	}

	protected void state(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String temp = request.getParameter("id");
		try {
			Integer id = Integer.valueOf(temp);
			OpenBuilder builder = openBuilderService.findById(id);
			builder.setState(builder.getState() == 0 ? 1 : 0);
			openBuilderService.setBuilderState(builder);
			JsonUtils.writeSuccessJson("更新成功!!", "", response);
		} catch (Exception e) {
			JsonUtils.writeFailJson("参数失败!!", response);
		}
		JsonUtils.writeFailJson("更新失败!!", response);
	}

	protected void open(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("state", 0);
			String cityId = request.getParameter("cityId");
			String areaId = request.getParameter("areaId");
			if (cityId != null) {
				try {
					Integer.valueOf(cityId);
					params.put("cityId", cityId);
				} catch (Exception e) {
				}
			}
			if (areaId != null) {
				try {
					Integer.valueOf(areaId);
					params.put("areaId", areaId);
				} catch (Exception e) {
				}
			}
			List<OpenBuilder> areas = openBuilderService.findAll(params);
			JsonUtils.writeSuccessPageJson("查询成功", areas, 0L, response);

		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

	protected void importExcel(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		try {
			String result = "";
			Enumeration em = request.getParameterNames();
			while (em.hasMoreElements()) {
				String name = (String) em.nextElement();
				String value = request.getParameter(name);
				if(!name.equals("action")){
					result = name;
				}
			}
			ObjectMapper mapper = new ObjectMapper();
			JavaType javaType = getCollectionType(ArrayList.class, OpenBuilder.class);
			List<OpenBuilder> builders =  (List<OpenBuilder>)mapper.readValue(result,javaType);

			for (OpenBuilder builder : builders) {
				try {
					String sql = "update " + OpenBuilder.class.getSimpleName().toLowerCase() + " set address = '"
							+ builder.getAddress() + "' where builderName = '" + builder.getBuilderName() + "'";
					System.err.println(sql);
					QueryRunner runner = new QueryRunner(getDataSource());
					runner.update(sql);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
		return new ObjectMapper().getTypeFactory().constructParametricType(collectionClass, elementClasses);
	}

}
